package com.dhecp.project.storage.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.dto.IndexConfigDto;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.core.utils.ReadExcel;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.storage.domain.DeliveryLogistics;
import com.dhecp.project.storage.domain.DeliveryLogisticsDetail;
import com.dhecp.project.storage.enums.DeliveryLogisticsEnum;
import com.dhecp.project.storage.mapper.DeliveryLogisticsMapper;
import com.dhecp.project.storage.service.DeliveryLogisticsDetailService;
import com.dhecp.project.storage.service.DeliveryLogisticsService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @program: kjecp
 * @description: 海外仓 控制层
 */
@Controller
@RequestMapping("/storage/deliveryLogisticsRK")
public class HWDeliveryLogisticsRKController extends BaseModuleController {

    private String prefix = "storage/deliveryLogisticsRK";
    private String moduleTable = ModuleTable.DELIVERY_LOGISTICSRK;

    @Autowired
    private DeliveryLogisticsMapper deliveryLogisticsMapper;
    @Autowired
    private DeliveryLogisticsDetailService deliveryLogisticsDetailService;
    @Autowired
    private DeliveryLogisticsService deliveryLogisticsService;
    @Autowired
    private SysDictionaryForFieldService sysDictionaryForFieldService;
    
    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    /**
     * @Description: 查询页 子列表数据
     */
    @RequiresPermissions("storage:deliveryLogisticsRK:view")
    @GetMapping("/indexConfig")
    @ResponseBody
    public AjaxResult indexConfig(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryLogistics()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");
    	
        IndexConfigDto dto = this.getIndexConfig(params);
        AjaxResult ajaxResult = AjaxResult.success(dto);
        return ajaxResult;
    }

    /**
     * @Description: 查询页 列表数据
     */
    @RequiresPermissions("storage:deliveryLogisticsRK:view")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("useIn", "rk");
        List<DeliveryLogistics> list = new ArrayList<DeliveryLogistics>();
        try {
            list = deliveryLogisticsService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 查询页 子列表数据
     */
    @RequiresPermissions("storage:deliveryLogistics:view")
    @GetMapping("/sonlist")
    @ResponseBody
    public AjaxResult sonlist(String bid) {
    	
    	DeliveryLogistics deliveryLogistics = deliveryLogisticsMapper.findByBid(bid);
    	
        try {

            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
            Map<String, Object> mapList = new HashMap<>();
            mapList.put("sonList", deliveryLogisticsDetailService.listByBidLogistics(deliveryLogistics.getBid()));
            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            
        	Map<String, Object> params = new HashMap<String, Object>();
            params.put("moduleTable", ModuleTable.DELIVERY_LOGISTICS_DETAIL);
            params.put("entity", new DeliveryLogisticsDetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("toolBarWidth", 0);
            mapList.put("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
            AjaxResult ajaxResult = AjaxResult.success(mapList);
            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

//    /**
//     * @Description: 查询页 子列表数据
//     */
//    @RequiresPermissions("storage:deliveryLogistics:list")
//    @GetMapping("/sonlist")
//    @ResponseBody
//    public AjaxResult sonlist(@RequestParam Map<String, Object> params) {
//        try {
//
//            params.put("moduleTable", moduleTable2);
//            params.put("entity", new DeliveryLogisticsDetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
//            params.put("toolBarWidth", 0);
//            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
//            Map<String, Object> mapList = new HashMap<>();
//            mapList.put("sonList", deliveryLogisticsService.querySonListByBid(params));
//            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
//            mapList.put("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
//            AjaxResult ajaxResult = AjaxResult.success(mapList);
//            return ajaxResult;
//        } catch (Exception e) {
//            return AjaxResult.error(this.getExceptionMessage(e));
//        }
//    }


    /**
     * @Description: 打开制单页
     * @Param: nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     */
    @RequiresPermissions("storage:deliveryLogisticsRK:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryLogistics()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/deliveryLogistics_edit"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 0;
        boolean vType = false;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("storage:deliveryLogistics:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }
        
        String bid = params.get("bid").toString();

        try {
            DeliveryLogistics businessData = deliveryLogisticsService.queryByBid(bid);
            Map<String, Object> headData = TypeUtils.entityToMap(businessData);        //表头的业务数据
            params.put("headData", headData); //表头的业务数据

            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            ModelAndView mv = this.openEditPage(params);

            mv.addObject("enableEdit", vType ? 0 : enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）
            if (businessData != null) {
                Map<String, Object> params2 = new HashMap<String, Object>();
                params2.put("moduleTable", moduleTable);
                params2.put("bidBox", businessData.getBidBox());
                mv.addObject("detailList", deliveryLogisticsService.querySonListByBid(params2));//明细数据
                mv.addObject("bid", businessData.getBid());//单号
            }

            return mv;
        } catch (Exception e) {
            return this.gotoModelAndViewErrorPage(e.getMessage());    //详细信息
        }

    }

    /**
     * 导出
     */
    @RequiresPermissions("storage:deliveryLogisticsRK:export")
    @Log(title = "海外仓发货物流数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryLogistics());

        List<DeliveryLogistics> list = deliveryLogisticsService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = sysDictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<DeliveryLogistics> util = new ExportExcelUtils<DeliveryLogistics>(moduleTable, new DeliveryLogistics());
        return util.exportExcel(list, fieldList, "海外仓发货装箱数据", "export");
    }


    /**
     * 打开入库页
     */
    //@RequiresPermissions("storage:deliveryLogisticsRK:stockIn")
    @GetMapping("/toStockIn")
    public ModelAndView toStockIn(@RequestParam Map<String, Object> params) {
    	
    	ModelAndView mv = this.getModelAndView();
    	String bid = params.get("bid").toString();
    	DeliveryLogistics deliveryLogistics = deliveryLogisticsService.queryByBid(bid);
    	if (deliveryLogistics.getStateName().equals(DeliveryLogisticsEnum.StateName.INIT.value)
    			|| deliveryLogistics.getStateName().equals(DeliveryLogisticsEnum.StateName.SUCCESS.value)) {
            AjaxResult ajaxResult = AjaxResult.error("该单据非已发货状态，无法操作");
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName("error/mv_error");
			return mv;
		} else if (!deliveryLogistics.getStateRkName().equals(DeliveryLogisticsEnum.StateRkName.INIT.value)) {
            AjaxResult ajaxResult = AjaxResult.error("非未入库状态，无法操作");
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName("error/mv_error");
			return mv;
		}
    	
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new DeliveryLogistics()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/toStockIn"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 0;
        boolean vType = false;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("storage:deliveryLogisticsRK:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }

        try {
            Map<String, Object> headData = TypeUtils.entityToMap(deliveryLogistics);        //表头的业务数据
            params.put("headData", headData); //表头的业务数据

            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            mv = this.openEditPage(params);

            mv.addObject("enableEdit", vType ? 0 : enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）
            if (deliveryLogistics != null) {
                Map<String, Object> params2 = new HashMap<String, Object>();
                params2.put("moduleTable", moduleTable);
                params2.put("bidBox", deliveryLogistics.getBidBox());
                mv.addObject("detailList", deliveryLogisticsService.querySonListByBid(params2));//明细数据
                mv.addObject("entity", deliveryLogistics);
            }

            return mv;
        } catch (Exception e) {
            return this.gotoModelAndViewErrorPage(e.getMessage());    //详细信息
        }

    }

    /**
     * 入库
     */
    //@RequiresPermissions("storage:deliveryLogisticsRK:stockIn")
    @Log(title = "海外仓物流订单入库", businessType = BusinessType.UPDATE)
    @PostMapping("/stockIn")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult stockIn(String bid, String vHwTo) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryLogisticsService.stockIn(bid, vHwTo);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 入库回退
     */
    //@RequiresPermissions("storage:deliveryLogisticsRK:refuse")
    @Log(title = "海外仓发货装箱回退", businessType = BusinessType.UPDATE)
    @PostMapping("/stockInBack")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult stockInBack(String bid) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryLogisticsService.stockInBack(bid);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 填写运单号
     */
    //@RequiresPermissions("storage:deliveryLogisticsRK:editWayBillNumber")
    @Log(title = "海外仓发货装箱填写运单号", businessType = BusinessType.UPDATE)
    @PostMapping("/editWayBillNumber")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editWayBillNumber(String bid, String wayBillNumber) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryLogisticsService.editWayBillNumber(bid, wayBillNumber);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 填写运单号
     */
    //@RequiresPermissions("storage:deliveryLogisticsRK:editWayBillNumber")
    @Log(title = "海外仓发货装箱填写预计发货时间", businessType = BusinessType.UPDATE)
    @PostMapping("/editTimeArrivePredict")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editTimeArrivePredict(String bid, String timeArrivePredict) {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = deliveryLogisticsService.editTimeArrivePredict(bid, timeArrivePredict);
        } catch (Exception e) {
        	e.printStackTrace();
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 批量导入表格
     */
    //@RequiresPermissions("storage:deliveryLogisticsRK:importBatch")
    @GetMapping("/toImportBatch")
    public ModelAndView toImportBatch() {
    	
        ModelAndView mv = this.getModelAndView();
        
        mv.setViewName(prefix + "/toImportBatch");
        return mv;

    }

    @PostMapping("/uploadAndReadExcelBatchImport")
    @ResponseBody
	public AjaxResult uploadAndReadExcelBatchImport(@RequestParam("file") MultipartFile uploadfile) throws Exception {
    	

		try {
			InputStream fileInputStream = uploadfile.getInputStream();
//	        BufferedInputStream bis = new BufferedInputStream(fileInputStream);
			
			// 文件初始名
			String sourceFilename = uploadfile.getOriginalFilename();
	    	if (!sourceFilename.endsWith(".xlsx")) {
				return AjaxResult.error("请按照模板xlsx进行导入");
			}
			List<List<String>> data = ReadExcel.getRowsByInputStream(fileInputStream, 0);
			
			List<TableDto.RowDto> rows = new ArrayList<TableDto.RowDto>();
			if (rows != null && rows.size() > 300) {
				return AjaxResult.error("导入数量不能超过300条");
			}
			for (int i = 1, index = 1; data != null && i < data.size(); i++) {
				List<String> row = data.get(i);
				
				String bid = row.get(0);
				String wayBillNumber = row.get(1);
				rows.add(new TableDto.RowDto(index, bid, wayBillNumber));
				index++;
			}
			TableDto dto = new TableDto(rows);
			return AjaxResult.success(dto);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("数据有误，请联系客服");
		}
	}
	@Data
	@AllArgsConstructor
	public static class TableDto{
		private List<RowDto> rows; // 货件清单数组
		
		@Data
		@AllArgsConstructor
		public static class RowDto {
			private int index; // 序号
			private String bid; // 海外仓物流订单号
			private String wayBillNumber; // 物流运单号
		}
	}
    
    /**
     * 批量新增商品库——数据提交
     */
    @Log(title = "批量导入海外仓物流运单号", businessType = BusinessType.INSERT)
    //@RequiresPermissions("storage:deliveryLogisticsRK:importBatch")
    @PostMapping("/importBatch")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult importBatch(String detailArr){
    	
    	if (detailArr == null || detailArr.length() == 0) {
			return AjaxResult.error("导入出错，请联系技术");
		}
    	JSONArray detailJA = JSON.parseArray(detailArr);
    	for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
	        try {
				String bid = detailJO.getString("bid");
				String wayBillNumber = detailJO.getString("wayBillNumber");
	        	deliveryLogisticsService.editWayBillNumber(bid, wayBillNumber);
	        
	        }catch (Exception e) {
	        	e.printStackTrace();
	            return AjaxResult.error(this.getExceptionMessage(e));
	        }
		}
        return AjaxResult.success("操作成功");
    }
}